package com.example.demo.demos.controller;

import com.example.demo.demos.model.Rating;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api/ratings")
public class RatingController {

    private static final Logger logger = LoggerFactory.getLogger(RatingController.class);
    private static final int MAX_QUEUE_SIZE = 100;
    private final Queue<Double> ratingsQueue = new ConcurrentLinkedQueue<>();
    private final AtomicInteger currentSize = new AtomicInteger(0);

    @PostMapping("/add")
    public ResponseEntity<String> addRating(@RequestBody String ratingJson) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Rating rating = mapper.readValue(ratingJson, Rating.class);

            if (currentSize.get() >= MAX_QUEUE_SIZE) {
                ratingsQueue.poll();
                currentSize.decrementAndGet();
                logger.info("队列已满，移除最早的评分数据");
            }

            ratingsQueue.offer(rating.getValue());
            currentSize.incrementAndGet();
            logger.info("成功接收到评分: {}", rating.getValue());
            return ResponseEntity.ok("评分已添加");
        } catch (Exception e) {
            logger.error("处理评分时发生错误: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body("无法处理评分数据");
        }
    }

    @GetMapping("/list")
    public ResponseEntity<List<Double>> listRatings() {
        List<Double> ratings = new ArrayList<>(ratingsQueue);
        logger.info("返回评分列表, 共计 {} 条数据", ratings.size());
        return ResponseEntity.ok(ratings);
    }
}
